package com.hong.arithmetic.disruptor;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
import java.util.stream.Stream;


/**
 * @author: csh
 * @Date: 2023/6/17 23:37
 * @Description:主测试方式
 */
public class DisruptorMain {
    public static void main(String[] args) {
        //开始时间
        Date start = new Date();
        //创建线程池
        ExecutorService executor = Executors.newCachedThreadPool();
        //初始化Disruptor  其中参数顺序如下：
        //  LongEvent新建
        // ringBufferSize大小一定要是2的N次方
        // executor为线程池
        Disruptor<LongEvent> disruptor = new Disruptor<LongEvent>(LongEvent::new, 1024 * 1024, executor);
        //连接消费者
        disruptor.handleEventsWith(new Consumer());
        //启动
        RingBuffer<LongEvent> ringBuffer = disruptor.start();
        //生产者
        Producer producer = new Producer();
        IntStream.range(0, 3000000)
                .parallel()
                .forEach(i -> {
                    ringBuffer.publishEvent(producer);
                });

        //关闭服务 关闭线程池
        disruptor.shutdown();
        executor.shutdown();
        Date end = new Date();
        System.out.println((end.getTime() - start.getTime()) / 1000 + "秒");
    }
}
